import os 
import sys 
import time 
import curses
import json 
import requests
import argparse 
from typing import List, Tuple 
from numalo.papers.pdf.pdf2words import pdf_read_text, pdf_text2words
from numalo.words.haici.haici import fetch_en2cn
from numalo.utils.cli import CliWindow
from numalo.utils.print import decorate_print


def refresh_multiline_interface(stdscr, lines):
    stdscr.clear()  # 清除屏幕内容
    for i, line in enumerate(lines):
        stdscr.addstr(i, 0, line)  # 在指定位置添加文本
    stdscr.refresh()  # 刷新屏幕



class Word:
    def __init__(self, en, cn=""):
        self._en = en 
        self._cn = cn 
    

    @property
    def en(self):
        return self._en 
    
    @property 
    def cn(self):
        if not self._cn:
            self._cn = fetch_en2cn(self.en)
        return self._cn 
        
    def get_cn(self):
        return self._cn 


class CliWinHandle(CliWindow):

    def __init__(self, cfg):
        super().__init__()
        self.Ffile = cfg.get("Ffile")
        self.Cfile = cfg.get("Cfile")
        self.Bfile = cfg.get("Bfile")


        pdfpath = cfg.get("pdfpath", "")
        
        if os.path.isfile(pdfpath):
            text = pdf_read_text(pdfpath)
            words = pdf_text2words(text)
            data = list() 
            for w in words:
                data.append(Word(w))
            self.dump_data2json(data, self.Cfile)


        self.FData = dict() 
        self.CData = dict() 
        self.BData = dict() 
        
        self.FData = self.load_json2data(self.Ffile)
        self.CData = self.load_json2data(self.Cfile)
        self.BData = self.load_json2data(self.Bfile)

        print(f"f: {len(self.FData)}, {len(self.CData)}, {len(self.BData)}")
        self.widx = 0 

        


    
    def __del__(self):
        self.dump_data2json(self.FData, self.Ffile)
        self.dump_data2json(self.CData, self.Cfile)
        self.dump_data2json(self.BData, self.Bfile)

        super().__del__()


    def load_json2data(self, file):
        res = list()
        if not file:
            return res 
        try:
            data = dict()
            with open(file, "r") as f:
                data = json.load(f)
            for k, v in data.items():
                res.append(Word(k, v))
        except:
            pass 
        return res 
    

    def dump_data2json(self, data: List[Word], file):
        if not file:
            return 
        try:
            with open(file, "w") as f:
                jdata = dict() 
                for d in data:
                    jdata[d.en] = d.get_cn()
                json.dump(jdata, f, indent=2, ensure_ascii=False)
        except:
            pass 
                

    def refresh(self, msg, *args, **kws):

        idx_len = len(self.CData)
        if idx_len < 1: 
            idx = 0
            k = ""
            v = ""
        else: 
            idx = self.widx % idx_len 
            k = self.CData[idx].en
            v = self.CData[idx].cn 
        nline = kws.get("nline", 20)

        msg = []
        msg.append("================================================================")
        msg.append("VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV")
        res = f"idx: [{len(self.FData):-5d}, {idx:-5d}/{idx_len:-5d}, {len(self.BData):-5d}] \n \nword: {decorate_print(k)} \ncn: {v}".replace("\n\n", "\n").split("\n") + [""] * nline 
        msg += res[:16]
        msg.append(f"[d]: 过滤不再出现， [n]: next")
        msg.append("================================================================")
        super().refresh(msg)

    def wait_key(self):
        # print("wait_key")

        while True:
            key = self.stdscr.getch()
            print(f", hello {chr(key)}")
            if len(self.CData) < 1:
                continue 
            if key == ord("n"):
                self.widx = (self.widx + 1) % len(self.CData)
                return 
            elif key == ord("p"):
                self.widx = (self.widx - 1) % len(self.CData) 
                return -1
            elif key == ord("s"):
                return   
            elif key == ord("b"):
                kv = self.CData.pop(self.widx)
                self.FData.append(kv)
                return  
            elif key == ord("f"):
                kv = self.CData.pop(self.widx)
                self.BData.append(kv)
                return 
            elif key == ord("q"):
                exit()
        return 1 


def showwords(cfg):
    file = cfg.get("src") 
    pdfpath = cfg.get("pdfpath", "")
    if file.startswith("http"):
        response = requests.get(file)
        with open(pdfpath, 'wb') as f:
            f.write(response.content)
        # os.system(f"curl -L {file} -o temp.pdf")
        file = pdfpath
    else:
        file = file 
    


    nline = 20 
    cliw = CliWinHandle(cfg)
    
    while True:
        print("hhh")
        cliw.refresh(None, nline=nline)
        cliw.wait_key()

        



parser = argparse.ArgumentParser(
    description="""
numalo.papers.showwords --pdfpath=temp.pdf --src=https://link.springer.com/content/pdf/10.1007/s11263-019-01247-4.pdf
numalo.papers.showwords --Cfile=word-c.json --Bfile=word-b.json
"""
)

parser.add_argument(
    "--src", type=str, default=""
)

parser.add_argument(
    "--Ffile", type=str, default=""
)

parser.add_argument(
    "--Cfile", type=str, default="word-c.json"
)

parser.add_argument(
    "--Bfile", type=str, default=""
)

parser.add_argument(
    "--pdfpath", type=str, default=""
)


def main():
    args = parser.parse_args()
    cfg = dict(
        src = args.src,
        Ffile = args.Ffile,
        Cfile = args.Cfile,
        Bfile = args.Bfile,
        pdfpath = args.pdfpath 
    )
    print(cfg)
    
    

    showwords(cfg)




if __name__ == "__main__":
    main() 
